﻿/*
 * 2008 (c) ralfoide at gmail com
 * Project: SharpFlow
 * License: GPL
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using sharpCash.HTTPClasses;

namespace Alfray.SharpFlow.Core {

    /// <summary>
    /// List of known financial institutions
    /// </summary>
    public class FIList {

        private string kPrefFile = "filist.xml";
        private List<FI> mFIList = new List<FI>();

        public FIList() {
        }

        public List<FI> list {
            get { return mFIList; }
        }

        /// <summary>
        /// Loads the FI list from the msn site.
        /// </summary>
        /// <returns>True if at least one FI was read</returns>
        public bool loadFromWeb() {
            mFIList.Clear();

            for (int i = 1; i < 4; i++) {
                string data = HTTPClass.HttpGet("http://moneycentral.msn.com/money/2006/mnynet/service/ols/filist.aspx?SKU=3&VER=6&T=" + i.ToString() + "&S=*&R=1&O=0&TEST=0", null, null, null);
                if (data != "") {
                    byte[] buf = Encoding.ASCII.GetBytes(data);
                    MemoryStream ms = new MemoryStream(buf);
                    XmlTextReader reader = new XmlTextReader(ms);
                    reader.WhitespaceHandling = WhitespaceHandling.Significant;
                    // skip XML header and find "fil"
                    if (reader.ReadToFollowing("fil")) {
                        for (bool ok = reader.ReadToDescendant("fi"); ok; ok = reader.ReadToFollowing("fi")) {
                            XmlReader fi_reader = reader.ReadSubtree();
                            if (fi_reader.ReadToDescendant("name") && fi_reader.Read()) {
                                string name = fi_reader.Value;
                                if (fi_reader.ReadToFollowing("guid") && fi_reader.Read()) {
                                    string guid = fi_reader.Value;

                                    mFIList.Add(new FI(name, guid));
                                }
                            }
                        }
                    }
                }
            }

            mFIList.Sort();
            return mFIList.Count > 0;
        }

        /// <summary>
        /// Saves the FI list to the settings XML file
        /// </summary>
        public void saveToSettingsFile() {
            string f = Alfray.SharpFlow.Utils.Misc.settingFileName(kPrefFile);

            XmlWriter w = new XmlTextWriter(f, System.Text.Encoding.UTF8);

            w.WriteStartDocument();
            w.WriteStartElement("fi-list");
            w.WriteAttributeString("version", "1.0");

            foreach (FI fi in mFIList) {
                w.WriteStartElement("fi");

                w.WriteStartElement("name");
                w.WriteString(fi.name);
                w.WriteEndElement();	// name

                w.WriteStartElement("guid");
                w.WriteString(fi.guid);
                w.WriteEndElement();	// guid

                w.WriteEndElement();	// fi
            }

            w.WriteEndElement(); // fi-list
            w.WriteEndDocument();
            w.Close();
        }

        /// <summary>
        /// Load FI list from the settings XML file.
        /// </summary>
        /// <returns>True if at least one FI was read.</returns>
        public bool loadFromSettingsFile() {
            string f = Alfray.SharpFlow.Utils.Misc.settingFileName(kPrefFile);

            if (!File.Exists(f))
                return false;

            try {
                XmlDocument doc = new XmlDocument();
                doc.Load(f);

                // not an XML?
                if (doc.DocumentElement == null)
                    return true;

                mFIList.Clear();

                foreach (XmlNode node in doc.SelectNodes("/fi-list/fi")) {
                    try {
                        XmlNode name_node = node.SelectSingleNode("name");
                        XmlNode guid_node = node.SelectSingleNode("guid");
                        System.Diagnostics.Debug.Assert(name_node != null && guid_node != null);

                        if (name_node != null && guid_node != null) {
                            string name = name_node.InnerText.Trim();
                            string guid = guid_node.InnerText.Trim();

                            if (name != String.Empty && guid != String.Empty) {
                                mFIList.Add(new FI(name, guid));
                            }
                        }
                    } catch (Exception ex) {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }

                return mFIList.Count > 0;
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return false;
        }
    }
}
